package com.simon.netty.demo2.Utils;

import io.netty.buffer.ByteBuf;

import java.io.*;

/**
 * Created by changf on 2017/7/14.
 */
public class ByteBufUtils {

    public static byte[] ByteBuffToBytes(ByteBuf datas){
     byte[] bytes=new byte[datas.readableBytes()];
        datas.readBytes(bytes);
        return bytes;
    }

    public static Object byteToObject(byte[] bytes){
        Object obj=null;
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream=null;
        try{
            objectInputStream=new ObjectInputStream(byteArrayInputStream);
            obj=objectInputStream.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                objectInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;

    }

    public static byte[] objectToByte(Object obj){
        byte[] bytes=null;
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream=null;
        try{

            objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            bytes=byteArrayOutputStream.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bytes;


    }
}
